// components/Chatbot.js。

import React, { useState } from 'react';
import axios from 'axios';

const Chatbot = () => {
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');

  const handleSendMessage = () => {
    if (inputMessage.trim() === '') return;

    const newMessages = [...messages, { type: 'user', text: inputMessage }];
    setMessages(newMessages);

    axios.post('http://127.0.0.1:5000/chatbot', { message: inputMessage })
      .then(response => {
        const botMessage = response.data.response;
        setMessages([...newMessages, { type: 'bot', text: botMessage }]);
      })
      .catch(error => {
        console.error('Error:', error);
      });

    setInputMessage('');
  };

  return (
    <div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
      <h1 style={{ textAlign: 'center' }}>智能聊天功能页面</h1>
      <div style={{ border: '1px solid #ccc', minHeight: '300px', maxHeight: '500px', overflowY: 'scroll', padding: '10px', marginBottom: '20px' }}>
        {messages.map((message, index) => (
          <div key={index} style={{ marginBottom: '10px', textAlign: message.type === 'user' ? 'right' : 'left' }}>
            <strong>{message.type === 'user' ? 'You: ' : 'Bot: '}</strong> {message.text}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <input
          type="text"
          value={inputMessage}
          onChange={e => setInputMessage(e.target.value)}
          style={{ flex: '1', marginRight: '10px', padding: '8px', fontSize: '16px', border: '1px solid #ccc', borderRadius: '4px' }}
          placeholder="请输入消息..."
        />
        <button onClick={handleSendMessage} style={{ padding: '8px 16px', fontSize: '16px', backgroundColor: '#007bff', color: '#fff', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>发送</button>
      </div>
    </div>
  );
};

export default Chatbot;
